package com.samphanie.auiu.biz_home.fragment.category

import android.os.Bundle
import android.util.SparseIntArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import com.samphanie.auiu.biz_home.R
import com.samphanie.auiu.biz_home.databinding.FragmentCategoryBinding
import com.samphanie.auiu.biz_home.api.categoryApiService
import com.samphanie.auiu.common.route.AuiuRoute
import com.samphanie.auiu.common.ui.component.AuiuBaseFragment
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse
import com.samphanie.auiu.biz_home.model.SubCategory
import com.samphanie.auiu.biz_home.model.TabCategory
import com.samphanie.auiu.common.ui.view.loadUrl
import com.samphanie.auiu.ui.tab.bottom.AuiuTabBottomLayout

class CategoryFragment : AuiuBaseFragment<FragmentCategoryBinding>() {

    private val SPAN_COUNT = 3
    private val subcategoryListCache = mutableMapOf<String, List<SubCategory>>()

    override fun getLayoutId(): Int {
        return R.layout.fragment_category
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        AuiuTabBottomLayout.clipBottomPadding(binding.rootContainer)
    }

    override fun initialize(savedInstanceState: Bundle?) {

        queryCategoryList()
    }

    private fun queryCategoryList() {
        categoryApiService().queryCategoryList()
            .enqueue(object : AuiuCallback<List<TabCategory>> {
                override fun onSuccess(response: AuiuResponse<List<TabCategory>>) {
                    if (response.successful() && response.data != null) {
                        onQueryCategoryListSuccess(response.data!!)
                    } else {
                        showEmptyView()
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    showEmptyView()
                }

            })
    }

    private fun onQueryCategoryListSuccess(data: List<TabCategory>) {
        if (!isAlive) return
        binding.emptyView.visibility = View.GONE
        binding.sliderView.visibility = View.VISIBLE

        binding.sliderView.bindMenuView(itemCount = data.size,
            onBindView = { holder, position ->
                val category = data[position]
                holder.findViewById<TextView>(R.id.menu_item_title)?.text = category.name
            }, onItemClick = { holder, position ->
                val category = data[position]
                val cateId = category.id
                if (subcategoryListCache.containsKey(cateId)) {
                    onQuerySubCategoryListSuccess(subcategoryListCache[cateId]!!)
                } else {
                    querySubCategoryList(cateId)
                }
            })
    }

    private fun querySubCategoryList(cateId: String) {
        categoryApiService().querySubCategoryList(cateId)
            .enqueue(object : AuiuCallback<List<SubCategory>> {
                override fun onSuccess(response: AuiuResponse<List<SubCategory>>) {
                    if (response.successful() && response.data != null) {
                        onQuerySubCategoryListSuccess(response.data!!)
                        if (!subcategoryListCache.containsKey(cateId)) {
                            subcategoryListCache[cateId] = response.data!!
                        }
                    }
                }

                override fun onFailed(throwable: Throwable) {

                }

            })
    }

    private val layoutManager = GridLayoutManager(context, SPAN_COUNT)
    private val groupSpanSizeOffset = SparseIntArray()

    private val spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
        override fun getSpanSize(position: Int): Int {
            var spanSize = 1
            val groupName = subCategoryList[position].groupName
            val nextGroupName = if (position + 1 < subCategoryList.size) subCategoryList[position+1].groupName else null

            if(groupName == nextGroupName) {
                spanSize = 1
            } else {
                // 当前位置和下一个位置 不在同一个分组
                // 1. 拿到当前组 position （所在组）在groupSpanSizeOffset 的索引下标
                // 2. 拿到当前组前面一组 存储的SpanSizeOffset 偏移量
                // 3. 给当前组最后一个item 分配 spansize count

                val indexOfKey = groupSpanSizeOffset.indexOfKey(position)
                val size = groupSpanSizeOffset.size()
                val lastGroupOffset = if (size <= 0) 0
                else if (indexOfKey >= 0) {
                    // 说明当前组的偏移量记录，已经存在了 groupSpanSizeOffset ，这个情况发生在上下滑动，
                    if (indexOfKey == 0) 0 else groupSpanSizeOffset.valueAt(indexOfKey - 1)
                } else {
                    // 说明当前组的偏移量记录，还没有存在于 groupSpanSizeOffset ，这个情况发生在 第一次布局的时候
                    // 得到前面所有组的偏移量之和
                    groupSpanSizeOffset.valueAt(size - 1)
                }
                //          3       -     (6     +    5               % 3  )第几列=0  ，1 ，2
                spanSize = SPAN_COUNT - (position + lastGroupOffset) % SPAN_COUNT
                if (indexOfKey < 0) {
                    // 得到当前组 和前面所有组的spansize 偏移量之和
                    val groupOffset = lastGroupOffset + spanSize - 1
                    groupSpanSizeOffset.put(position, groupOffset)
                }
            }
            return spanSize
        }

    }

    private val subCategoryList = mutableListOf<SubCategory>()
    private val decoration = CategoryItemDecoration({ position ->
        subCategoryList[position].groupName
    }, SPAN_COUNT)

    private fun onQuerySubCategoryListSuccess(data: List<SubCategory>) {
        if (!isAlive) return
        decoration.clear()
        groupSpanSizeOffset.clear()
        subCategoryList.clear()
        subCategoryList.addAll(data)

        if (layoutManager.spanSizeLookup != spanSizeLookup) {
            layoutManager.spanSizeLookup = spanSizeLookup
        }

        binding.sliderView.bindContentView(
            itemCount = data.size,
            itemDecoration = decoration,
            layoutManager = layoutManager,
            onBindView = { holder, position ->
                val subCategory = data[position]
                if (!subCategory.subCategoryIcon.isNullOrBlank()) {
                    holder.findViewById<ImageView>(R.id.content_item_image)?.loadUrl(subCategory.subCategoryIcon)
                }
                holder.findViewById<TextView>(R.id.content_item_title)?.text = subCategory.subCategoryName
            },
            onItemClick = { holder, position ->
                // 跳转商品类目的商品列表页
                val subcategory = data[position]
                val bundle = Bundle()
                bundle.putString("cateId", subcategory.cateId)
                bundle.putString("subCateId", subcategory.id)
                bundle.putString("cateTitle", subcategory.subCategoryName)
                AuiuRoute.startActivity(requireContext(), bundle, AuiuRoute.Destination.GOODS_LIST)
                // Toast.makeText(context, "you touch me: $position", Toast.LENGTH_SHORT).show()
            }
        )
    }

    private fun showEmptyView() {
        if (!isAlive) return

        binding.sliderView.visibility = View.GONE
        binding.emptyView.visibility = View.VISIBLE
        binding.emptyView.setIcon(R.string.if_empty3)
        binding.emptyView.setDesc(getString(R.string.list_empty_desc))
        binding.emptyView.setButton(getString(R.string.list_empty_action)) {
            queryCategoryList()
        }

    }
}